﻿using Covid.Server.Data;
using Covid.Server.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Covid.Server.Services
{

    /// <summary>
    /// 员工 仓储实现
    /// </summary>
    public class EmployeeRepository : IEmployeeRepository
    {

        private readonly MyDbContext _context;
        /// <summary>
        /// 通过构造函数注入dbContext
        /// </summary>
        public EmployeeRepository(MyDbContext context)
        {
            _context = context;
        }


        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="employee"></param>
        /// <returns></returns>
        public async Task<Employee> AddAsync(Employee employee)
        {
            await _context.Employees.AddAsync(employee);

            var count = await _context.SaveChangesAsync();
            if (count != 1) {
                throw new Exception("新增失败！");
            }
            return employee;
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task DeleteAsync(int id)
        {
            var exist = await _context.Employees.FindAsync(id);
            if (exist == null) {
                throw new Exception("未找到该员工！");
            }
            _context.Employees.Remove(exist);
            var count = await _context.SaveChangesAsync();
            if (count != 1)
            {
                throw new Exception("删除失败！");
            }
        }


        /// <summary>
        ///  根据部门编码获得该部门所有的员工信息
        /// </summary>
        /// <param name="departmentId"></param>
        /// <returns></returns>
        public async Task<IList<Employee>> GetForDepartmentAsync(int departmentId)
        {
            var employees = await _context.Employees.Where(u => u.DepartmentId.Equals(departmentId)).ToListAsync();
            return employees;
        }


        /// <summary>
        /// 获得某一个员工
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Employee> GetOneAsync(int departmentid,int id)
        {
            var one = await _context.Employees.SingleOrDefaultAsync(u => u.DepartmentId.Equals(departmentid) && u.Id.Equals(id));
            return one;
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="emplyee"></param>
        /// <returns></returns>
        public async Task UpdateAsync(Employee emplyee)
        {
            _context.Employees.Attach(emplyee);
            _context.Employees.Update(emplyee);
            var count = await _context.SaveChangesAsync();
            if (count != 1)
            {
                throw new Exception("修改失败！");
            }
        }

    }
}
